from datetime import datetime

from sqlalchemy_serializer import SerializerMixin

from app import dBSession
from app.Models.BaseModel import BaseModel
from app.Models.Model import ErrorLog
from app.Vendor.Decorator import classTransaction


class ErrorLogs(ErrorLog, BaseModel, SerializerMixin):

    @classTransaction
    def get_one(self, error_log):
        res = dBSession.query(ErrorLogs).filter(ErrorLogs.id == error_log.id).first()
        if not res:
            return None
        res = res.to_dict()
        if res['created_at']:
            res['created_at'] = res['created_at'].strftime('%Y-%m-%d %H:%M:%S')
        return res

    # 增加
    @classTransaction
    def add(self, error_log):
        error_log.create_time = datetime.now()
        dBSession.add(error_log)
        dBSession.flush()
        return error_log.id

    @classTransaction
    def get_list(self, filters: set, offset: int = 0, limit: int = 15):
        res = {}
        res['page'] = {}
        res['page']['count'] = dBSession.query(ErrorLogs).filter(*filters).count()
        res['list'] = []
        res['page']['total_page'] = self.get_page_number(res['page']['count'], limit)
        res['page']['current_page'] = offset
        if offset != 0:
            offset = (offset - 1) * limit
        if res['page']['count'] > 0:
            res['list'] = dBSession.query(ErrorLogs).filter(*filters).offset(offset).limit(limit).all()
            res['list'] = [c.to_dict() for c in res['list']]
            for c in res['list']:
                if c['created_at']:
                    c['created_at'] = c['created_at'].strftime('%Y-%m-%d %H:%M:%S')
        return res
